import React from 'react'
import axios from 'axios'
import '../css/goods.scss'
import 'bootstrap/dist/css/bootstrap.min.css'
import { Provider, connect } from 'react-redux'
import { mapStateToProps, mapDispatchToProps } from '../redux/action'

class Goods extends React.Component {
  constructor() {
    super()
    this.state = {
      arr: []
    }
  }
  componentDidMount() {
    axios.get('data.json').then(result => {
      // console.log(result)
      this.setState({
        arr: result.data
      })
    })
  }
  //加入购物车;
  addCart(info) {
    //拿到id首先要判断是否在store中
    //如果存在则数量加一  如果不在需要将数据push到store中
    var cartinfo = {
      id: info.id,
      goodsname: info.goodsname,
      price: info.price,
      num: 1,
      src: info.src
    }
    var cart = this.props.cart
    // console.log(this.props.cart)
    var s = cart.findIndex((value, index, cart) => {
      return value.id == info.id
    })
    if (s == -1) {
      //需要把cartinfo 存入store中
      this.props.add(cartinfo)
    } else {
      //需要改变数量
      this.props.addNum(s)
    }
  }
  render() {
    return (
      <div>
        <ul className="list">
          {this.state.arr.map(item => {
            return (
              <li key={item.id}>
                <span>
                  <img src={item.src} />
                </span>
                <span>{item.goodsname}</span>
                <span>{item.price}</span>
                <input
                  type="button"
                  value="加入购物车"
                  className="btn btn-success"
                  onClick={() => this.addCart(item)}
                />
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
}

Goods = connect(
  mapStateToProps,
  mapDispatchToProps
)(Goods)
export default Goods
